package pl.us.ij.plugins.segmentation.infrastructure;


import ij.IJ;
import ij.ImagePlus;
import pl.us.ij.plugins.segmentation.Trace;
import pl.us.ij.plugins.segmentation.infrastructure.exceptions.BreakCommandException;
import pl.us.ij.plugins.segmentation.localization.Localization;

import java.io.CharArrayWriter;
import java.io.PrintWriter;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * @author Przemek
 */
public class CommandRunner extends Thread {
    ICommand command;
    ImagePlus imagePlus;
    CommandParams params;

    public CommandRunner(ImagePlus imagePlus, CommandParams params, ICommand command) {
        if (command == null)
            throw new IllegalArgumentException("command");

        this.command = command;
        this.imagePlus = imagePlus;
        this.params = params;

        command.setImage(this.imagePlus);

        setPriority(Math.max(getPriority() - 2, MIN_PRIORITY));
        start();
    }

    @Override
    public void run() {
        try {
            Trace.log("Starting " + command.getName() + "...");
            long start = System.currentTimeMillis();

            this.command.run();

            long period = (System.currentTimeMillis() - start);
            Trace.log("Command completed after: " + period / 1000f + "s (" + period + "ms)");
        }
        catch (OutOfMemoryError e) {
            IJ.outOfMemory(command.getName());
            Trace.log("Out of memory!");
        }
        catch (BreakCommandException e) {
            IJ.showMessage(command.getName() + Localization.getString("commandRunner.error"), e.getMessage());
        }
        catch (Exception e) {
            CharArrayWriter stackSink = new CharArrayWriter();
            e.printStackTrace(new PrintWriter(stackSink));
            Trace.log(stackSink.toString());
            IJ.showStatus("");
        }
    }
}

